const AudioManager = {
    audioContext: null,
    oscillator: null,
    gainNode: null,
    isAlarmPlaying: false,

    init() {
        // Audio context will be created when needed due to browser autoplay policies
    },

    startAlarm() {
        if (!this.audioContext) {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        }

        if (!this.isAlarmPlaying) {
            this.oscillator = this.audioContext.createOscillator();
            this.gainNode = this.audioContext.createGain();

            this.oscillator.connect(this.gainNode);
            this.gainNode.connect(this.audioContext.destination);

            this.oscillator.frequency.setValueAtTime(800, this.audioContext.currentTime);
            this.oscillator.type = 'square';

            this.gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);

            this.oscillator.start();
            this.isAlarmPlaying = true;

            // 添加闪烁效果
            document.getElementById('controls').classList.add('alarm-animation');

            // 蜂鸣器节奏
            this.alarmInterval = setInterval(() => {
                if (this.isAlarmPlaying && this.oscillator) {
                    this.oscillator.frequency.setValueAtTime(800, this.audioContext.currentTime);
                    setTimeout(() => {
                        if (this.isAlarmPlaying && this.oscillator) {
                            this.oscillator.frequency.setValueAtTime(1000, this.audioContext.currentTime);
                        }
                    }, 200);
                }
            }, 400);
        }
    },

    stopAlarm() {
        if (this.isAlarmPlaying && this.oscillator) {
            this.oscillator.stop();
            this.oscillator = null;
            this.isAlarmPlaying = false;

            // 移除闪烁效果
            document.getElementById('controls').classList.remove('alarm-animation');

            // 清除间隔
            if (this.alarmInterval) {
                clearInterval(this.alarmInterval);
                this.alarmInterval = null;
            }
        }
    }
};